package org.flyframework.rpc
{
	import mx.rpc.AsyncResponder;
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	
	/**
	 * HTTP...
	 * 
	 * @author Ben Edwards
	 */
	public class FlyHTTP
	{
		
		public var service:HTTPService;
		public var token:AsyncToken;
		
		private var responders:Array = new Array();
//		private var resultHandlers:Array = new Array();
//		private var faultHandlers:Array = new Array();
		
		
		//--------------------------------------------------------------------------
		// Init
		//--------------------------------------------------------------------------
		
		public function FlyHTTP( service:HTTPService )
		{
			this.service = service;
		}
		
		
		//--------------------------------------------------------------------------
		// Callables
		//--------------------------------------------------------------------------
		
		public function responder( responder:IResponder ):FlyHTTP
		{
			this.responders.push( responder );
			
			// token has already been created, add the responder
			if( this.token )
			{
				this.token.addResponder( responder );
			}
			
			return this;
		}
		
		public function respond( resultHandler:Function, faultHandler:Function, flags:uint=0 ):FlyHTTP
		{
			return responder( new FlyResponder( resultHandler, ignoreFault ) );
		}
		
		public function result( resultHandler:Function, flags:uint=0 ):FlyHTTP
		{
//			this.resultHandlers.push( resultHandler );
			
			return respond( resultHandler, ignoreFault );
		}
		
		public function fault( faultHandler:Function, flags:uint=0 ):FlyHTTP
		{
//			this.faultHandlers.push( faultHandler );
			
			return respond( ignoreResult, faultHandler );
		}
		
		
		//--------------------------------------------------------------------------
		// 
		//--------------------------------------------------------------------------
		
		public function send( parameters:Object=null ):FlyHTTP
		{
			this.token = this.service.send( parameters );
			
			// attach responders to token
			var responder:IResponder;
			for each( responder in this.responders )
			{
				token.addResponder( responder );
			}
			
			/*
			// attach listeners to token
			var handler:Function;
			for each( handler in this.resultHandlers )
			{
				token.addEventListener( ResultEvent.RESULT, handler );
			}
			for each( handler in this.faultHandlers )
			{
				token.addEventListener( FaultEvent.FAULT, handler );
			}
			*/
			
			return this;
		}
		
		
		protected function ignoreResult( resultEvent:ResultEvent, token:AsyncToken=null ):void
		{
			// ignore
		}
		
		protected function ignoreFault( faultEvent:FaultEvent, token:AsyncToken=null ):void
		{
			// ignore
		}
		
	}
}